﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using CWB.Web.DB;

namespace CWB.Web.CacheLayer
{
    public static class BouCache
    {
        private static Hashtable boucache = new Hashtable();
        private static readonly object syncRoot = new object();

        public static List<BouUserCacheInfo> getBouCache()
        {
            List<BouUserCacheInfo> lbuci = new List<BouUserCacheInfo>() { };
            lbuci = boucache.Values.Cast<BouUserCacheInfo>().ToList();
            return lbuci;
        }

        public static void Remove(string username)
        {
            lock (syncRoot)
            {
                if ((boucache.ContainsKey(username)))
                {
                    boucache.Remove(username);
                }
            }
        }

        public static BouUserCacheInfo Get(string username)
        {
            if ((boucache.ContainsKey(username)))
            {
                return (BouUserCacheInfo)boucache[username];
            }
            else
            {
                throw new Exception(string.Format("The Backoffice User is not exist({0})", username));
            }
        }

        public static void Add(DbModuleBbu u)
        {
            if ((boucache.ContainsKey(u.username)))
            {
                boucache.Remove(u.username);
            }
            boucache.Add(u.username, new BouUserCacheInfo()
            {
                u = u,
                ExpireDataTime = DateTime.Now.AddHours(12)
            });
        }

        public static bool isExpired(Trading trading)
        {
            if (boucache.ContainsKey(trading.userName))
            {
                BouUserCacheInfo buci = (BouUserCacheInfo)boucache[trading.userName];
                if (buci.ExpireDataTime > DateTime.Now)
                {
                    return !(buci.u.chk == trading.chk);
                }
                else
                {
                    boucache.Remove(trading.userName);
                    return true;
                }
            }
            else
            {
                return true;
            }
        }

        public class BouUserCacheInfo
        {
            public DbModuleBbu u { get; set; }
            public DateTime ExpireDataTime { get; set; }
        }
    }
}
